package com.wyzz.hr.action;

import java.io.File;
import java.util.*;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import com.wyzz.hr.base.BaseAction;
import com.wyzz.hr.base.BaseDownloadAction;
import com.wyzz.hr.base.BasePdfExport;
import com.wyzz.hr.bo.IDepartmentBO;
import com.wyzz.hr.bo.IEmpAddConfBo;
import com.wyzz.hr.bo.IEmpContractBo;
import com.wyzz.hr.bo.IEmpEduHisBo;
import com.wyzz.hr.bo.IEmpEvalBo;
import com.wyzz.hr.bo.IEmpJobHisBo;
import com.wyzz.hr.bo.IEmpQuitBo;
import com.wyzz.hr.bo.IEmpRelationsBo;
import com.wyzz.hr.bo.IEmpRewardBo;
import com.wyzz.hr.bo.IEmpTrainHisBo;
import com.wyzz.hr.bo.IEmpTransferBo;
import com.wyzz.hr.bo.IEmployeeBo;
import com.wyzz.hr.bo.TemplateService;
import com.wyzz.hr.pojo.Department;
import com.wyzz.hr.pojo.Empaddconf;
import com.wyzz.hr.pojo.Empcontract;
import com.wyzz.hr.pojo.Empeval;
import com.wyzz.hr.pojo.Emphistoryjob;
import com.wyzz.hr.pojo.Emphistorytrain;
import com.wyzz.hr.pojo.Employee;
import com.wyzz.hr.pojo.Empquit;
import com.wyzz.hr.pojo.Emprelations;
import com.wyzz.hr.pojo.Empreward;
import com.wyzz.hr.pojo.Emptransfer;
import com.wyzz.hr.spring.SpringBeanFactory;
import com.wyzz.hr.util.Environment;
import com.wyzz.hr.util.impl.PropertiesFileConfigManager;

public class EmpInfoCard extends BaseDownloadAction {

	public EmpInfoCard() {
		templateName = "print_empInfo";
	}

	public String execute() throws Exception {
		IEmployeeBo empBo = (IEmployeeBo) SpringBeanFactory.getBean("empBo");
		if (StringUtils.isEmpty(empId))
			empId = getCurrentEmpNo();
		String fetch[] = { Employee.PROP_EMP_TYPE, Employee.PROP_EMP_DEPT_NO,
				Employee.PROP_EMP_PB_NO, Employee.PROP_EMP_LOCATION_NO,
				Employee.PROP_EMP_BENEFIT_TYPE };
		setEmployee(empBo.loadEmp(empId, fetch));
		Department dept = employee.getEmpDeptNo();
		IDepartmentBO departmentBo = (IDepartmentBO) SpringBeanFactory
				.getBean("departmentBO");
		List allResultList = departmentBo.FindEnabledDepartment();
		if (dept.getDepartmentParentId() != null) {
			String turnDeptId = dept.getDepartmentParentId().getId();
			boolean turnIdExist;
			do {
				turnIdExist = false;
				Iterator it = allResultList.iterator();
				do {
					if (!it.hasNext())
						break;
					Department deptInWhile = (Department) it.next();
					if (deptInWhile.getId().equals(turnDeptId)) {
						turnIdExist = true;
						String deptName = (new StringBuilder()).append(
								deptInWhile.getDepartmentName()).append("-")
								.append(dept.getDepartmentName()).toString();
						dept.setDepartmentName(deptName);
						if (deptInWhile.getDepartmentParentId() == null)
							turnDeptId = null;
						else
							turnDeptId = deptInWhile.getDepartmentParentId()
									.getId();
					}
				} while (true);
			} while (turnDeptId != null && turnIdExist);
		}
		if (getEmployee() == null) {
			addErrorInfo("\u9519\u8BEF\u7684\u8BF7\u6C42\u53C2\u6570\uFF0C\u8981\u67E5\u770B\u7684\u5458\u5DE5\u4E0D\u5B58\u5728\u6216\u5DF2\u7ECF\u88AB\u5220\u9664\uFF01");
			return "noemp";
		}
		String empMsn = employee.getEmpMsn();
		if (empMsn != null && !"".equals(empMsn)) {
			if (empMsn.startsWith("QQ:")) {
				connectionType = "QQ";
				connectionNo = empMsn.replace("QQ:", "");
			} else if (empMsn.startsWith("WW:")) {
				connectionType = "\u65FA\u65FA";
				connectionNo = empMsn.replace("WW:", "");
			} else {
				connectionType = "MSN";
				connectionNo = empMsn;
			}
		} else {
			connectionType = "\u5373\u65F6\u901A\u8BAF";
		}
		setStatus(empBo.getEmpStatus());
		IEmpJobHisBo empJobHisBo = (IEmpJobHisBo) BaseAction
				.getBean("empJobHisBo");
		ehjList = empJobHisBo.search(empId);
		IEmpEduHisBo empEduHisBo = (IEmpEduHisBo) BaseAction
				.getBean("empEduHisBo");
		eheList = empEduHisBo.search(empId);
		IEmpTrainHisBo empTrainHisBo = (IEmpTrainHisBo) BaseAction
				.getBean("empTrainHisBo");
		ehtList = empTrainHisBo.search(empId);
		IEmpRelationsBo empRelationsBo = (IEmpRelationsBo) BaseAction
				.getBean("empRelationsBo");
		erelList = empRelationsBo.search(empId);
		IEmpAddConfBo empAddConfBo = (IEmpAddConfBo) BaseAction
				.getBean("empAddConfBo");
		empaddconfList = empAddConfBo.listByTable("empAdditional");
		int size = empaddconfList.size();
		for (int i = 0; i < size; i++) {
			Empaddconf eac = (Empaddconf) empaddconfList.get(i);
			int index = eac.getEadcSeq().intValue();
			eac.setFieldName((new StringBuilder()).append("empAdditional")
					.append(index).toString());
			BeanUtils.setProperty(eac, "value", BeanUtils.getProperty(employee,
					(new StringBuilder()).append("empAdditional").append(index)
							.toString()));
			if ("select".equals(eac.getEadcFieldType()))
				eac.setFieldValueList(Arrays.asList(eac.getEadcFieldValue()
						.split(",")));
		}

		IEmpContractBo empContractBo = (IEmpContractBo) getBean("empContractBo");
		contractList = empContractBo.searchByEmpNo(empId);
		IEmpQuitBo empQuit = (IEmpQuitBo) getBean("empQuitBo");
		quitList = empQuit.searchByEmpNo(empId);
		IEmpRewardBo empReward = (IEmpRewardBo) getBean("empRewardBo");
		rewardList = empReward.findRewardByEmpNo(empId);
		IEmpTransferBo empTransfer = (IEmpTransferBo) getBean("empTransferBo");
		transferList = empTransfer.findTransferByEmpNo(empId);
		IEmpEvalBo empEval = (IEmpEvalBo) getBean("empEvalBo");
		evalList = empEval.findEvalByEmpNo(empId);
		TemplateService templateService = (TemplateService) SpringBeanFactory
				.getBean("ftlTemplateService");
		if (!templateService.checkPDFTemplateExist(templateName)) {
			printContent = "\u6A21\u677F\u4E0D\u5B58\u5728\uFF01";
			return "success";
		}
		processWrapString();
		empImageFile = employee.getEmpImage();
		Map modal = new HashMap();
		modal.put("employee", employee);
		modal.put("ehjList", ehjList);
		modal.put("eheList", eheList);
		modal.put("ehtList", ehtList);
		modal.put("erelList", erelList);
		modal.put("empaddconfList", empaddconfList);
		modal.put("contractList", contractList);
		modal.put("quitList", quitList);
		modal.put("rewardList", rewardList);
		modal.put("transferList", transferList);
		modal.put("evalList", evalList);
		modal.put("empImageFile", empImageFile);
		String empImagePath = copyImageToWeb(employee.getEmpImage());
		employee.setEmpImage(empImagePath);
		printContent = templateService.getPDFContent(templateName, modal);
		if ("pdf".equals(resultType)) {
			if (printContent.indexOf("&nbsp;") > -1)
				printContent = printContent.replaceAll("&nbsp;", "");
			String fileNameWithPath = BasePdfExport.pdfExport(printContent);
//			deleteFile(empImageFile);
			if (download(fileNameWithPath, (new StringBuilder()).append(
					employee.getEmpName()).append("(").append(
					employee.getEmpDistinctNo()).append(")").append(".pdf")
					.toString()))
				return "download";
		}
		return "success";
	}

	private void processWrapString() {
		if (employee.getEmpDeptNo() != null)
			employee.getEmpDeptNo().setDepartmentName(
					BasePdfExport.processWrap(employee.getEmpDeptNo()
							.getDepartmentName(), 240, 5, 12));
		if (employee.getEmpPbNo() != null)
			employee.getEmpPbNo().setPbName(
					BasePdfExport.processWrap(
							employee.getEmpPbNo().getPbName(), 85, 5, 12));
		if (employee.getEmpEmail() != null)
			employee.setEmpEmail(BasePdfExport.processWrap(employee
					.getEmpEmail(), 85, 5, 12));
		if (employee.getEmpSpeciality() != null)
			employee.setEmpSpeciality(BasePdfExport.processWrap(employee
					.getEmpSpeciality(), 90, 5, 12));
		if (employee.getEmpCityNo() != null)
			employee.setEmpCityNo(BasePdfExport.processWrap(employee
					.getEmpCityNo(), 90, 5, 12));
		if (employee.getEmpResidenceLoc() != null)
			employee.setEmpResidenceLoc(BasePdfExport.processWrap(employee
					.getEmpResidenceLoc(), 90, 5, 12));
		if (employee.getEmpProfileLoc() != null)
			employee.setEmpProfileLoc(BasePdfExport.processWrap(employee
					.getEmpProfileLoc(), 90, 5, 12));
		if (employee.getEmpHomeAddr() != null)
			employee.setEmpHomeAddr(BasePdfExport.processWrap(employee
					.getEmpHomeAddr(), 160, 5, 12));
		if (employee.getEmpCurrAddr() != null)
			employee.setEmpCurrAddr(BasePdfExport.processWrap(employee
					.getEmpCurrAddr(), 160, 5, 12));
		for (int i = 0; empaddconfList != null && i < empaddconfList.size(); i++) {
			Empaddconf add = (Empaddconf) empaddconfList.get(i);
			add.setEadcFieldName(BasePdfExport.processWrap(add
					.getEadcFieldName(), 100, 5, 12));
			add.setEadcFieldValue(BasePdfExport.processWrap(add
					.getEadcFieldValue(), 240, 5, 12));
		}

		for (int i = 0; ehjList != null && i < ehjList.size(); i++) {
			Emphistoryjob ehj = (Emphistoryjob) ehjList.get(i);
			ehj.setEhjPosition(BasePdfExport.processWrap(ehj.getEhjPosition(),
					100, 5, 12));
			ehj.setEhjDescription(BasePdfExport.processWrap(ehj
					.getEhjDescription(), 280, 5, 12));
		}

		for (int i = 0; ehtList != null && i < ehtList.size(); i++) {
			Emphistorytrain eht = (Emphistorytrain) ehtList.get(i);
			eht.setEhtCourse(BasePdfExport.processWrap(eht.getEhtCourse(), 180,
					5, 12));
		}

		for (int i = 0; erelList != null && i < erelList.size(); i++) {
			Emprelations ere = (Emprelations) erelList.get(i);
			ere.setErelContactInfo(BasePdfExport.processWrap(ere
					.getErelContactInfo(), 100, 5, 12));
		}

		for (int i = 0; contractList != null && i < contractList.size(); i++) {
			Empcontract contract = (Empcontract) contractList.get(i);
			contract.setEctComments(BasePdfExport.processWrap(contract
					.getEctComments(), 120, 5, 12));
		}

		for (int i = 0; transferList != null && i < transferList.size(); i++) {
			Emptransfer transfer = (Emptransfer) transferList.get(i);
			transfer.setEftReason(BasePdfExport.processWrap(transfer
					.getEftReason(), 80, 5, 12));
			transfer.setEftComments(BasePdfExport.processWrap(transfer
					.getEftComments(), 80, 5, 12));
		}

		for (int i = 0; evalList != null && i < evalList.size(); i++) {
			Empeval eval = (Empeval) evalList.get(i);
			eval.setEeRate(BasePdfExport.processWrap(eval.getEeRate(), 80, 5,
					12));
			eval.setEeComments(BasePdfExport.processWrap(eval.getEeComments(),
					100, 5, 12));
		}

		for (int i = 0; rewardList != null && i < rewardList.size(); i++) {
			Empreward reward = (Empreward) rewardList.get(i);
			reward.setErContent(BasePdfExport.processWrap(
					reward.getErContent(), 280, 5, 12));
		}

		for (int i = 0; quitList != null && i < quitList.size(); i++) {
			Empquit quit = (Empquit) quitList.get(i);
			quit.setEqReason(BasePdfExport.processWrap(quit.getEqReason(), 160,
					5, 12));
			quit.setErComments(BasePdfExport.processWrap(quit.getErComments(),
					160, 5, 12));
		}

	}

	private String copyImageToWeb(String fileName) {
		String empImagePath = null;
		String imagePath;
		File fromFile;
		imagePath = PropertiesFileConfigManager.getInstance().getProperty(
				"sys.user.image.path");
		String filePath = (new StringBuilder()).append(
				Environment.getFileHome()).append(imagePath).toString();
		System.out.println(filePath);
		empImagePath = (new StringBuilder()).append(filePath).append(fileName)
				.toString();
		fromFile = new File(empImagePath);
		if (StringUtils.isEmpty(fileName) || !fromFile.exists()) {
			empImagePath = "../../resource/images/None.JPG";
			return empImagePath;
		}
		File toForder;
		String toForderStr = (new StringBuilder()).append(
				Environment.getApplicationHome()).append("file/").append(
				imagePath).toString();
		toForder = new File(toForderStr);
		if (!toForder.exists())
			toForder.mkdir();
		if ((new File((new StringBuilder()).append(toForderStr)
				.append(fileName).toString())).exists())
			return (new StringBuilder()).append("../../file/")
					.append(imagePath).append(fileName).toString();
		try {
			FileUtils.copyFileToDirectory(fromFile, toForder);
			return (new StringBuilder()).append("../../file/")
					.append(imagePath).append(fileName).toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String deleteEmpImage(String fileName) {
		deleteFile(fileName);
		return "SUCC";
	}

	private void deleteFile(String fileName) {
		String imagePath = PropertiesFileConfigManager.getInstance()
				.getProperty("sys.user.image.path");
		String toForderStr = (new StringBuilder()).append(
				Environment.getApplicationHome()).append("file/").append(
				imagePath).toString();
		String filePath = (new StringBuilder()).append(toForderStr).append(
				fileName).toString();
		File file = new File(filePath);
		if (!file.exists()) {
			return;
		} else {
			file.delete();
			return;
		}
	}

	public Employee getEmployee() {
		return employee;
	}

	public void setEmployee(Employee employee) {
		this.employee = employee;
	}

	public List getEhjList() {
		return ehjList;
	}

	public void setEhjList(List ehjList) {
		this.ehjList = ehjList;
	}

	public List getEheList() {
		return eheList;
	}

	public void setEheList(List eheList) {
		this.eheList = eheList;
	}

	public List getEhtList() {
		return ehtList;
	}

	public void setEhtList(List ehtList) {
		this.ehtList = ehtList;
	}

	public List getEmpaddconfList() {
		return empaddconfList;
	}

	public void setEmpaddconfList(List empaddconfList) {
		this.empaddconfList = empaddconfList;
	}

	public List getTransferList() {
		return transferList;
	}

	public void setTransferList(List transferList) {
		this.transferList = transferList;
	}

	public List getRewardList() {
		return rewardList;
	}

	public void setRewardList(List rewardList) {
		this.rewardList = rewardList;
	}

	public List getEvalList() {
		return evalList;
	}

	public void setEvalList(List evalList) {
		this.evalList = evalList;
	}

	public List getStatus() {
		return status;
	}

	public void setStatus(List status) {
		this.status = status;
	}

	public List getContractList() {
		return contractList;
	}

	public void setContractList(List contractList) {
		this.contractList = contractList;
	}

	public List getQuitList() {
		return quitList;
	}

	public void setQuitList(List quitList) {
		this.quitList = quitList;
	}

	public String getEmpId() {
		return empId;
	}

	public void setEmpId(String empId) {
		this.empId = empId;
	}

	public List getErelList() {
		return erelList;
	}

	public void setErelList(List erelList) {
		this.erelList = erelList;
	}

	public String getConnectionType() {
		return connectionType;
	}

	public void setConnectionType(String connectionType) {
		this.connectionType = connectionType;
	}

	public String getConnectionNo() {
		return connectionNo;
	}

	public void setConnectionNo(String connectionNo) {
		this.connectionNo = connectionNo;
	}

	public String getPrintContent() {
		return printContent;
	}

	public void setPrintContent(String printContent) {
		this.printContent = printContent;
	}

	public String getResultType() {
		return resultType;
	}

	public void setResultType(String resultType) {
		this.resultType = resultType;
	}

	public String getEmpImageFile() {
		return empImageFile;
	}

	public void setEmpImageFile(String empImageFile) {
		this.empImageFile = empImageFile;
	}

	private static final long serialVersionUID = 1L;
	private Employee employee;
	private List ehjList;
	private List eheList;
	private List ehtList;
	List erelList;
	private List empaddconfList;
	private List transferList;
	private List rewardList;
	private List evalList;
	private List status;
	private List contractList;
	private List quitList;
	private String empId;
	private String connectionType;
	private String connectionNo;
	private String printContent;
	private String resultType;
	private String templateName;
	private String empImageFile;
}
